今天要學習Component組件,組件的功能就像是一個容器,他可以把多個HTML元素裝在一起,也就是說可以把網頁拆成不同部分來寫,React會把這些組件結合在一起,進而形成一個網頁。
創建組件有兩種方式,第一種是class,第二種是function。class較少人使用了,大部分都使用fuction。
function App() {
return (
<div>hello world</div>
)
}
例如這個function App()就代表一個網頁,這個在JavaScript裡面寫HTML就是JSX,至於瀏覽器能夠讀懂JSX是因為JSX經過Vite裡面的編譯工具,轉換成JavaScript。總結,可以把JSX看成JavaScript,只是JSX可以在裡面寫html
創建一個組件並使用:
//創建一個組件
function MyComponent(){
return <h1>你好</h1>
}
//使用MyComponent()這個組件
function App() {
return (
<div><MyComponent></MyComponent></div>
)
}
至於APP.jsx的export default App是把APP組件導出去,並在main.jsx中的import App from './App.jsx’導入APP組件
//React把物件轉換成html的過程
ReactDOM.createRoot(document.getElementById('root')).render(
//document.getElementById('root')>>使用DOM api取得id名稱為root的元素
<React.StrictMode>
<App /> //根組件
</React.StrictMode>,
)
通常會使用Pascal Case(將每一個單詞的開頭寫成大寫),用來區分組件以及HTML元素
組件又分為parent component父組件以及child component子組件,以下面為例,MyComponent 組件被包在App()裡面,所以是子組件,而App為父組件 (樹狀結構)
function App() {
return (
<div><MyComponent /></div>
)
}
組件也可以重複使用
通常會把每個組件獨立成新檔案
export default ChildComponent;
再import到App.jsx
import ChildComponent from "./ChildComponent"
function MyComponent(){
return <ChildComponent />
}
學習影片出處:https://youtu.be/aBTiZfShe-4?si=Igb2aKz3sefA97A5